import React, { useEffect, useRef, useState } from 'react';
import styles from './index.less';

interface SeamlessScrollProps {
  data: any[]; // 数据列表
  speed?: number; // 滚动速度（像素/秒），默认 50
  direction?: 'horizontal' | 'vertical'; // 滚动方向，默认水平
  itemWidth?: number; // 每个项目的宽度（水平滚动时必需）
  itemHeight?: number; // 每个项目的高度（垂直滚动时必需）
  renderItem: (item: any, index: number) => React.ReactNode; // 渲染每一项
  className?: string;
  hoverPause?: boolean; // 鼠标悬停时暂停，默认 true
}

/**
 * 无缝循环滚动组件
 * 实现首尾相连的循环滚动效果
 */
const Index: React.FC<SeamlessScrollProps> = ({
                                                         data,
                                                         speed = 50,
                                                         direction = 'horizontal',
                                                         itemWidth,
                                                         itemHeight,
                                                         renderItem,
                                                         className = '',
                                                         hoverPause = true,
                                                       }) => {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [isPaused, setIsPaused] = useState(false);

  // 复制数据以实现无缝滚动
  const displayData = [...data, ...data];

  useEffect(() => {
    if (!scrollRef.current || data.length === 0) return;

    const scrollElement = scrollRef.current;
    let animationId: number;
    let currentPosition = 0;

    // 计算总长度
    const totalLength = direction === 'horizontal'
      ? (itemWidth || 0) * data.length
      : (itemHeight || 0) * data.length;

    const animate = () => {
      if (!isPaused) {
        currentPosition += speed / 60; // 60fps

        // 当滚动到一半时重置位置，实现无缝循环
        if (currentPosition >= totalLength) {
          currentPosition = 0;
        }

        if (direction === 'horizontal') {
          scrollElement.style.transform = `translateX(-${currentPosition}px)`;
        } else {
          scrollElement.style.transform = `translateY(-${currentPosition}px)`;
        }
      }

      animationId = requestAnimationFrame(animate);
    };

    animationId = requestAnimationFrame(animate);

    return () => {
      if (animationId) {
        cancelAnimationFrame(animationId);
      }
    };
  }, [data, speed, direction, itemWidth, itemHeight, isPaused]);

  const handleMouseEnter = () => {
    if (hoverPause) {
      setIsPaused(true);
    }
  };

  const handleMouseLeave = () => {
    if (hoverPause) {
      setIsPaused(false);
    }
  };

  return (
    <div
      className={`${styles.container} ${direction === 'vertical' ? styles.vertical : styles.horizontal} ${className}`}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      <div ref={scrollRef} className={styles.scrollContent}>
        {displayData.map((item, index) => (
          <div
            key={index}
            className={styles.scrollItem}
            style={{
              width: direction === 'horizontal' ? itemWidth : undefined,
              height: direction === 'vertical' ? itemHeight : undefined,
            }}
          >
            {renderItem(item, index % data.length)}
          </div>
        ))}
      </div>
    </div>
  );
};

export default Index;
